<template>
  <div style="padding: 24px 12px">
    <el-timeline v-if="showContent && momentList && momentList.length > 0">
      <el-timeline-item
        v-for="(item, index) in momentList"
        :key="index"
        :timestamp="item.label"
        placement="top"
      >
        <main-content
          :flowData="item.data"
          :presetContent="presetContent"
          @overide="handleOveride"
        />
      </el-timeline-item>
    </el-timeline>
    <div v-else>无流量数据</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import dayjs from "dayjs";
import useFlowStore from "@/store/flow.js";
import MainContent from "./MainContent.vue";
import { cumulate, arrange } from "../../utils";
import airportData from "./airportData.json";

const flowStore = useFlowStore();
const momentList = ref([]);
const showContent = ref(true);

const presetContent = ref();
const handleOveride = async ({ value, index }) => {
  showContent.value = false;
  presetContent.value[index] = value;
  generateMomentList();
  await nextTick();
  showContent.value = true;
};

const generateMomentList = () => {
  momentList.value = [];
  if (flowStore.rawData.length == 0) return null;
  let minute = Math.floor(new Date().getMinutes() / 30) * 30;
  let startIndex =
    dayjs().minute(minute).second(0).diff(flowStore.begTime, "minute") / 30;
  let arrangedData = arrange(
    cumulate(flowStore.rawData, 2, 4),
    flowStore.tags,
    flowStore.begTime,
    2
  );
  if (!arrangedData || arrangedData.length == 0) return null;
  for (let i = 0; i < 6; i++) {
    let data = arrangedData[startIndex + i];
    let label =
      dayjs()
        .minute(minute)
        .add(30 * i, "minute")
        .format("HH:mm") +
      " ~ " +
      dayjs()
        .minute(minute)
        .add(30 * i, "minute")
        .add(1, "hour")
        .format("HH:mm");
    momentList.value.push({ label, data });
  }
};

let timer = null;
onMounted(() => {
  generateMomentList();
  presetContent.value = JSON.parse(JSON.stringify(airportData));
  timer = setInterval(() => generateMomentList(), 2 * 60 * 1000);
});

onUnmounted(() => {
  clearInterval(timer);
});
</script>
